﻿using System;

using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using facebook;
using facebook.Schema;
using System.Configuration;

namespace FacebookApp
{
    public partial class Admins_Ebook : Page
    {
        private static bool Insert;
        private static string user_id = "-1";
        private static DataTable friends = null;
        private static Ebook epost;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["WB_UserId"] != null)
                    user_id = Session["WB_UserId"].ToString();                
                Session["folder"] = "Ebook";
                
                ShowDll();
                BindGrid();
            }
            if (Session["WB_GroupUser_Id"].ToString().Equals("1"))
            {
                pngroupuser.Visible = true;
            }
        }

        private void BindGrid()
        {
            if (ddlgroupuser.SelectedIndex > 0)
            {
                if (dllCatelogy_Id.SelectedIndex > 0)
                {
                    grdEbook.DataSource = EbookService.Ebook_GetByTop("", " Category_Id = '" + dllCatelogy_Id.SelectedValue + "' and " + " CreatedBy = '" + ddlgroupuser.SelectedValue + "'", " CreateDate DESC ");
                    grdEbook.DataBind();

                }
                else
                {
                    grdEbook.DataSource = EbookService.Ebook_GetByTop("", " CreatedBy = '" + ddlgroupuser.SelectedValue + "'", " CreateDate DESC ");
                    grdEbook.DataBind();
                }
            }
            else
            {
                if (dllCatelogy_Id.SelectedIndex > 0)
                {
                    grdEbook.DataSource = EbookService.Ebook_GetByTop("", " Category_Id = '" + dllCatelogy_Id.SelectedValue + "'", " CreateDate DESC ");
                    grdEbook.DataBind();

                }
                else
                {
                    grdEbook.DataSource = EbookService.Ebook_GetByTop("", "", " CreateDate DESC ");
                    grdEbook.DataBind();
                }
            }
        }

        protected string Format_Price(string Price)
        {
            return FunctionClass.Format_Price(Price);
        }

        protected void btnThem_Click(object sender, EventArgs e)
        {
            pnShow.Visible = false;
            pnUpdate.Visible = true;
            ControlClass.ResetControlValues(this);
            Session["upload"] = null;
            Insert = true;
        }

        protected void btnXoa_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridItem item = default(DataGridItem);
                for (int i = 0; i < grdEbook.Items.Count; i++)
                {
                    item = grdEbook.Items[i];
                    if (item.ItemType == ListItemType.AlternatingItem | item.ItemType == ListItemType.Item)
                    {
                        if (((CheckBox)item.FindControl("ChkSelect")).Checked)
                        {
                            string strId = item.Cells[1].Text;
                            try
                            {
                                EbookService.Ebook_Delete(strId);
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                grdEbook.CurrentPageIndex = 0;
                BindGrid();
            }
            catch
            {
            }
        }

        protected void grdEbook_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            var strCA = new EbookInfo();
            strCA.Id = e.CommandArgument.ToString();
            if (e.CommandName == "Edit")
            {
                Ebook dt = EbookService.Ebook_GetById(strCA.Id);
                txtId.Text = dt.Id.ToString();
                //txtCatgory_Id.Text = dt.Category_Id.ToString();
                ddlcatogory.SelectedValue = dt.Category_Id.ToString();
                txtName.Text = dt.Name.ToString();
                //txtImage.Text = dt.Image.ToString();
                Session["upload"] = dt.Image.ToString();

                txtFile_Upload.Text = dt.File_Upload.ToString();
                txtPromotion.Text = dt.Promotion.ToString();
                //txtDetail.Text = dt.Detail.ToString();
                FCKdetail.Value = dt.Detail.ToString();

                txtPrice.Text = dt.Price.ToString().Replace(".0000", "");
                txtPriceNew.Text = dt.PriceNew.ToString().Replace(".0000", "");
                //txtStatus.Text = dt.Status.ToString();
                ddlStatus.SelectedValue = dt.Status.ToString();
                //txtNumView.Text = dt.NumView.ToString();
                txtSize.Text = dt.Size.ToString();
                //txtPublisher_Id.Text = dt.Publisher_Id.ToString();
                ddlpublisher.SelectedValue = dt.Publisher_Id.ToString();

                txtYearPub.Text = dt.YearPub.ToString();
                txtQuantity.Text = dt.Quantity.ToString();
                txtNumPage.Text = dt.NumPage.ToString();
                dllAuthor_Id_Update.SelectedValue = dt.Author_Id.ToString();
                txtWeight.Text = dt.Weight.ToString();
                //txtNumLike.Text = dt.NumLike.ToString();
                //txtNumBought.Text = dt.NumBought.ToString();
                ddtisfree.SelectedValue = dt.isFree.ToString();
                ddlisonline.SelectedValue = dt.isOnlineView.ToString();
                //txtCreatedBy.Text = dt.CreatedBy.ToString();
                txtOrder.Text = dt.Order.ToString();
                pnUpdate.Visible = true;
                pnShow.Visible = false;
            }
            else
                if (e.CommandName == "Delete")
                {
                    EbookService.Ebook_Delete(strCA.Id);
                    BindGrid();
                }
                else
                    if (e.CommandName == "PostWall")
                {
                    epost = EbookService.Ebook_GetById(strCA.Id);
                    getpost();
                    pnUpdate.Visible = false;
                    pnShow.Visible = false;
                    pnPost.Visible = true;
                }
        }

        protected void lblBack_Click(object sender, EventArgs e)
        {
            pnUpdate.Visible = false;
            pnShow.Visible = true;
            Insert = false;
            BindGrid();
        }

        protected void lblUpdate_Click(object sender, EventArgs e)
        {
            string image = Session["upload"] == null ? "~/Data/Images/" + Session["folder"] + "/no-image.jpg" : Session["upload"].ToString();

            #region[TestInput]

            if (txtName.Text.Trim().Equals(""))
            {
                WebMsgBox.Show("Name not null!");
                txtName.Focus();
                return;
            }

            if (txtPrice.Text.Trim().Equals(""))
            {
                WebMsgBox.Show("Price not null!");
                txtPrice.Focus();
                return;
            }

            if (txtQuantity.Text.Trim().Equals(""))
            {
                WebMsgBox.Show("Quantity not null!");
                txtQuantity.Focus();
                return;
            }

            #endregion

            var obj = new EbookInfo();
            obj.Id = txtId.Text;
            // obj.Category_Id = txtCatgory_Id.Text;
            obj.Category_Id = ddlcatogory.SelectedValue;
            obj.Name = txtName.Text;
            //obj.Image = txtImage.Text;
            obj.Image = image;
            obj.File_Upload = txtFile_Upload.Text;
            //obj.File_Upload = image;
            obj.Promotion = txtPromotion.Text;
            obj.Detail = FCKdetail.Value;
            obj.Price = txtPrice.Text;
            obj.PriceNew = txtPriceNew.Text.Equals("") ? "0" : txtPriceNew.Text;
            obj.Status = ddlStatus.SelectedValue;
            obj.Size = txtSize.Text.Equals("") ? "0" : txtSize.Text;
            obj.Publisher_Id = ddlpublisher.SelectedValue;
            obj.YearPub = txtYearPub.Text.Equals("") ? "0" : txtYearPub.Text;
            obj.Quantity = txtQuantity.Text.Equals("") ? "0" : txtQuantity.Text;
            obj.NumPage = txtNumPage.Text.Equals("") ? "0" : txtNumPage.Text;
            obj.Author_Id = dllAuthor_Id_Update.SelectedValue;
            obj.Weight = txtWeight.Text.Equals("") ? "0" : txtWeight.Text;
            //obj.NumLike = txtNumLike.Text;
            //obj.NumBought = txtNumBought.Text;
            obj.isFree = ddtisfree.SelectedValue;
            obj.isOnlineView = ddlisonline.SelectedValue;

            if (Session["WB_UserId"] != null)
                obj.CreatedBy = Session["WB_UserId"].ToString();
            else
                obj.CreatedBy = "1";

            obj.Order = txtOrder.Text;
            if (Insert)
            {
                obj.Id = EbookService.Ebook_Insert(obj);//neu la insert thi gan lai id vua insert                
            }
            else
            {
                EbookService.Ebook_Update(obj);
            }

            if (cbpost.Checked)
            {
                posttowall("Sản phẩm mới", obj.Name, obj.Promotion, obj.Id, obj.Category_Id, ddlcatogory.SelectedItem.Text, obj.Image.Replace("~/", ""));
            }

            pnShow.Visible = true;
            pnUpdate.Visible = false;
            Insert = false;
            BindGrid();
        }

        protected void grdEbook_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            grdEbook.CurrentPageIndex = e.NewPageIndex;
            BindGrid();
        }

        private void ShowDll()
        {
            dllCatelogy_Id.Items.Add(new ListItem("-----All-----", "-1"));
            ddlgroupuser.Items.Add(new ListItem("-----All-----", "-1"));
            ddlgroupuser.Items.Add(new ListItem("-----Me-----", user_id.ToString()));
            List<User> _user = UserService.User_GetByTop("", "Id <> " + user_id, "");
            foreach (User u in _user)
            {
                ddlgroupuser.Items.Add(new ListItem(u.UserName, u.Id.ToString()));
            }
            ddlgroupuser.SelectedIndex = 1;
            ddlgroupuser.DataBind();


            List<Category> _category = new List<Category>();
            _category = CategoryService.Category_GetByAll();
            for (int i = 0; i < _category.Count; i++)
            {
                ddlcatogory.Items.Add(new ListItem(_category[i].Name.ToString(), _category[i].Id.ToString()));
                dllCatelogy_Id.Items.Add(new ListItem(_category[i].Name.ToString(), _category[i].Id.ToString()));
            }
            ddlcatogory.DataBind();
            dllCatelogy_Id.DataBind();

            List<Author> _author = new List<Author>();
            _author = AuthorService.Author_GetByAll();
            for (int i = 0; i < _author.Count; i++)
            {
                dllAuthor_Id_Update.Items.Add(new ListItem(_author[i].Name.ToString(), _author[i].Id.ToString()));

            }
            dllAuthor_Id_Update.DataBind();

            List<Publisher> _publisher = new List<Publisher>();
            _publisher = PublisherService.Publisher_GetByAll();
            for (int i = 0; i < _publisher.Count; i++)
            {
                ddlpublisher.Items.Add(new ListItem(_publisher[i].Name.ToString(), _publisher[i].Id.ToString()));
            }
            ddlpublisher.DataBind();

            ListItem _true = new ListItem("True", "True");
            ListItem _false = new ListItem("False", "False");
            ddlStatus.Items.Add(new ListItem("True", "True"));
            ddlStatus.Items.Add(new ListItem("False", "False"));
            ddlStatus.SelectedIndex = 0;
            ddlStatus.DataBind();

            ddtisfree.Items.Add(_true);
            ddtisfree.Items.Add(_false);
            ddtisfree.SelectedIndex = 1;
            ddtisfree.DataBind();

            ddlisonline.Items.Add(_true);
            ddlisonline.Items.Add(_false);
            ddlisonline.SelectedIndex = 1;
            ddlisonline.DataBind();

        }

        protected void btnshow_Click(object sender, EventArgs e)
        {
            BindGrid();            
        }

        protected void grdEbook_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            ListItemType itemType = e.Item.ItemType;
            if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
            {
                if (itemType == ListItemType.Header)
                {
                    object checkBox = e.Item.FindControl("chkSelectAll");
                    if ((checkBox != null))
                    {
                        ((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
                    }
                }
                else
                {
                    string tableRowId = grdEbook.ClientID + "_row" + e.Item.ItemIndex.ToString();
                    e.Item.Attributes.Add("id", tableRowId);
                    object checkBox = e.Item.FindControl("chkSelect");
                    if ((checkBox != null))
                    {
                        e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
                        e.Item.Attributes.Add("onMouseOut",
                                              "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex + ")");
                        ((CheckBox)checkBox).Attributes.Add("onClick",
                                                             "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex +
                                                             ")");
                    }
                }
            }
        }

        protected void posttowall(string _header, string _nameproduct, string _description, string id, string group_id, string group_name, string pathimage)
        {
            string headerlinkapp = ConfigurationSettings.AppSettings["fb_headerpath"].ToString();
            string domain = ConfigurationSettings.AppSettings["fb_domain"].ToString();
            string header = _header;//"Sản phẩm mới";
            string _link = headerlinkapp + "Pages/ProductDetail.aspx?Category_Id=" + group_id + "&Id=" + id + "";
            attachment attachment = new attachment();

            attachment.caption = headerlinkapp;
            attachment.name = _nameproduct;// "Tên sản phẩm";
            attachment.href = _link;
            attachment.description = _description;// "Mô tả sản phẩm";
            attachment.properties = new attachment_property()
            {
                category = new attachment_category()
                {
                    href = headerlinkapp + "Pages/ListGroupProduct.aspx?Id=" + group_id + "&GroupName=" + group_name.Replace(" ", "_") + "",
                    text = group_name//"humor"
                }
                //,
                //ratings = "5 stars"
            };
            attachment.media = new List<attachment_media>(){new attachment_media_image()
                                    {                                        
                                        src = domain + pathimage,//"http://fbapps.somee.com/Styles/Images/Koala.jpg",
                                        href =_link//"http://icanhascheezburger.com/2009/04/22/funny-pictures-bursting-with-joy/"
                                    }};
            List<action_link> action_link = new List<action_link>() { new action_link() { 
                text = "Make by your way",
                href = headerlinkapp } };
            //WebMsgBox.Show(pathimage);
            Master.API.stream.publish(header, attachment, action_link, Master.API.uid.ToString(), 1814236399);
        }

        /// <summary>
        /// ////////////////////////////////////post your friend's wall
        /// </summary>

        public void getpost()
        {
            if (friends != null)
                BindGridPost();
            else
            {
                friends = new DataTable();
                friends.Columns.Add("Id");
                friends.Columns.Add("pic_small");
                friends.Columns.Add("name");

                int countlimit = 0;
                IList<facebook.Schema.user> fr = Master.API.friends.getUserObjects();
                for (int i = 0; i < fr.Count; i++)
                {
                    //WebMsgBox.Show(fr[0].is_app_user.ToString());
                    if (fr[i].is_app_user.ToString() == "True")
                    {
                        AddRow(fr[i].uid.ToString(), fr[i].pic_big, fr[i].name);
                        countlimit++;
                    }
                    if (countlimit == 20)
                        break;
                }
                BindGridPost();
            }
        }

        protected void grdPost_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            ListItemType itemType = e.Item.ItemType;
            if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
            {
                if (itemType == ListItemType.Header)
                {
                    object checkBox = e.Item.FindControl("chkSelectAll");
                    if ((checkBox != null))
                    {
                        ((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
                    }
                }
                else
                {
                    string tableRowId = grdPost.ClientID + "_row" + e.Item.ItemIndex.ToString();
                    e.Item.Attributes.Add("id", tableRowId);
                    object checkBox = e.Item.FindControl("chkSelect");
                    if ((checkBox != null))
                    {
                        e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
                        e.Item.Attributes.Add("onMouseOut",
                                              "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex + ")");
                        ((CheckBox)checkBox).Attributes.Add("onClick",
                                                             "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex +
                                                             ")");
                    }
                }
            }
        }

        protected void grdPost_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            grdPost.CurrentPageIndex = e.NewPageIndex;
            BindGridPost();
        }

        private void BindGridPost()
        {
            grdPost.DataSource = friends;
            grdPost.DataBind();
        }

        protected void grdPost_ItemCommand(object source, DataGridCommandEventArgs e)
        { }

        protected void AddRow(string id, string pic_small, string name)
        {
            DataRow rows = friends.NewRow();
            rows["Id"] = id;
            rows["pic_small"] = pic_small;
            rows["name"] = name;

            friends.Rows.Add(rows);
        }
        protected void btpost_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridItem item = default(DataGridItem);
                if (epost != null)
                {
                    string productname = CategoryService.Category_GetById(epost.Category_Id.ToString()).Name;
                    for (int i = 0; i < grdPost.Items.Count; i++)
                    {
                        item = grdPost.Items[i];
                        if (item.ItemType == ListItemType.AlternatingItem | item.ItemType == ListItemType.Item)
                        {
                            if (((CheckBox)item.FindControl("ChkSelect")).Checked)
                            {
                                string strId = item.Cells[1].Text;
                                try
                                {

                                    posttofriendwall(strId, "Sản phẩm mới", epost.Name, epost.Promotion, epost.Id.ToString()
                                            , epost.Category_Id.ToString(), productname, epost.Image.Replace("~/", ""));
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                    WebMsgBox.Show("Post successful");
                }
                grdPost.CurrentPageIndex = 0;
                BindGridPost();
            }
            catch
            {
            }
        }

        protected void posttofriendwall(string uid, string _header, string _nameproduct, string _description, string id, string group_id, string group_name, string pathimage)
        {
            string headerlinkapp = ConfigurationSettings.AppSettings["fb_headerpath"].ToString();
            string domain = ConfigurationSettings.AppSettings["fb_domain"].ToString();
            string header = _header;//"Sản phẩm mới";
            string _link = headerlinkapp + "Pages/ProductDetail.aspx?Category_Id=" + group_id + "&Id=" + id + "";
            attachment attachment = new attachment();

            attachment.caption = headerlinkapp;
            attachment.name = _nameproduct;// "Tên sản phẩm";
            attachment.href = _link;
            attachment.description = _description;// "Mô tả sản phẩm";
            attachment.properties = new attachment_property()
            {
                category = new attachment_category()
                {
                    href = headerlinkapp + "Pages/ListGroupProduct.aspx?Id=" + group_id + "&GroupName=" + group_name.Replace(" ", "_") + "",
                    text = group_name//"humor"
                }
                //,
                //ratings = "5 stars"
            };
            attachment.media = new List<attachment_media>(){new attachment_media_image()
                                    {                                        
                                        src = domain + pathimage,//"http://fbapps.somee.com/Styles/Images/Koala.jpg",
                                        href =_link//"http://icanhascheezburger.com/2009/04/22/funny-pictures-bursting-with-joy/"
                                    }};
            List<action_link> action_link = new List<action_link>() { new action_link() { 
                text = "Make by your way",
                href = headerlinkapp } };
            //WebMsgBox.Show(pathimage);
            Master.API.stream.publish(header, attachment, action_link, uid, 1814236399);
            //Master.API.notifications.send(uid, "New", "user_to_user");
        }

        protected void lblBack2_Click(object sender, EventArgs e)
        {
            pnUpdate.Visible = false;
            pnShow.Visible = true;
            pnPost.Visible = false;
           // Insert = false;
        }
    }

}